define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'other-page'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'agent/orderfen/index',
                    add_url: 'agent/orderfen/add',
                    edit_url: 'agent/orderfen/edit',
                    del_url: 'agent/orderfen/del',
                    multi_url: 'agent/orderfen/multi',
                    detail_url: 'agent/orderfen/detail',
                    status_url: 'agent/orderfen/status',//审核链接
                    import_url: 'agent/orderfen/import',
                    can_url: 'agent/orderfen/can',//作废
                    send_url:'agent/order/send',//
                    download_url:'agent/orderfen/download',//模板下载
                    stat_url:'agent/orderfen/stat',//统计
                    table: 'order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                queryParams: function (params) {
                  //这里可以追加搜索条件
                  var filter = JSON.parse(params.filter);
                  var op = JSON.parse(params.op);
                  //这里可以动态赋值，比如从URL中获取admin_id的值，filter.admin_id=Fast.api.query('admin_id');
                  params.filter = JSON.stringify(filter);
                  params.op = JSON.stringify(op);
                  return params;
                },
                columns: [
                    [
                        // {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'nb', title: __('订单编号')},
                        // {field: 'status', title: __('审核状态'),visible: false,searchList: [{id:'-1',name:'订单作废'},{id:'0',name:'订单待审核'},{id:'1',name:'订单审核通过'},{id:'2',name:'发货审核通过'},{id:'3',name:'订单完成'}]},
                        // {field: 'deliverystatus', title: __('出库/发货'),visible: false,searchList: [{id:'-1',name:'订单作废'},{id:'0',name:'备货中\\代发货'},{id:'1',name:'已发货\\待审核\\发货已完成'},{id:'2',name:'已发货\\待审核\\发货未完成'},{id:'3',name:'确认收货\\已完成'}]},
                        {field: 'userid_text', title: __('创建人')},
                        {field: 'nameAgent', title: __('分公司')},
                        {field: 'order_price', title: __('合计码洋'),visible: true},
                        {field: 'check_order', title: __('合计实洋'),visible: true},
                        // {field: 'status_text', title: __('付款状态'), formatter: Controller.api.formatter.paystatus,operate: false},
                        {field: 'status_text', title: __('审核状态'), formatter: Controller.api.formatter.status,operate: false},
                        {field: 'deliverystatus_text', title: __('出库/发货'),formatter: Controller.api.formatter.deliverystatus,operate: false},
                        // {field: 'orderdate', title: __('付款日期'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        //操作栏,默认有编辑、删除或排序按钮,可自定义配置buttons来扩展按钮
                        {
                          field: 'operate',
                          width: "240px",
                          title: __('Operate'),
                          table: table,
                          events: Table.api.events.operate,
                          buttons: [
                            {
                              name: 'detail',
                              title: __('发货'),
                              text:'发货',
                              extend:"data-area='[\"70%\",\"70%\"]'",
                              classname: 'btn btn-xs btn-primary btn-dialog',
                              icon: 'fa fa-list',
                              url: 'agent/orderfen/edit',
                              hidden:function (row) {
                                if(row.status == 8)
                                {
                                  return true
                                }
                                if(row.deliverystatus == 0)
                                {
                                  return false;
                                }
                                return true;
                              }
                            },
                              {
                                  name: 'send',
                                  title: __('图书发货'),
                                  text:'图书发货',
                                  extend:"data-area='[\"70%\",\"70%\"]'",
                                  classname: 'btn btn-xs btn-primary btn-dialog',
                                  icon: 'fa fa-list',
                                  url: 'agent/order/send/type/1',
                                  hidden:function (row) {
                                      if(row.status == 8)
                                      {
                                          return true
                                      }
                                      if(row.deliverystatus == 0)
                                      {
                                          return false;
                                      }
                                      return true;
                                  }
                              },
                            {
                              name: 'detail',
                              title: __('订单详情'),
                              text:'订单详情',
                              extend:"data-area='[\"70%\",\"70%\"]'",
                              classname: 'btn btn-xs btn-primary btn-dialog',
                              icon: 'fa fa-list',
                              url: 'agent/orderfen/detail'
                            },
                            {
                              name: 'can',
                              icon: 'fa fa-trash',
                              title: __('作废'),
                              text:'作废',
                              extend: 'data-toggle="tooltip"',
                              classname: 'btn btn-xs btn-danger btn-can',
                              hidden:function (row) {
                                if(row.status == 8)
                                {
                                  return true;
                                }
                                return false;
                              }
                            }
                          ],
                          // formatter: Table.api.formatter.operate
                          formatter: Table.api.formatter.buttons
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
          //杨柳
          var index = $("#ultable").attr("data-listidx");
          layer.load("加载中");
          setTimeout(function() {//异步处理，防止冒泡事件，select未加载成功
            layer.closeAll();
            $(".btn-append").click(function () {
              htmlAdd();
            });
          },500);
          //删除
          $("#ultable").on("click",".del",function(){
            var ind = $(this).attr('data-id');
            $("#sele"+ind).selectPageClear();
            $("#tr"+ind).remove();
            table_sort();
          });
          function htmlAdd(data = {id:'',price:''}) {
            var str='<tr id="tr'+index+'">' +
              '<td>1</td>' +
              '<td ><input  data-id="'+index+'"  data-rule="required"  style="width:280px" id="sele'+index+'" data-source="ajax/getgoods"   data-search-field="cname,cnames"  data-field="cname" data-primary-key="id" name="row[goods][goods_id]['+index+'][]"  class="form-control selectpage wuji" style="width:100%" placeholder="请选择商品"  type="text" value="'+data.id+'" autocomplete="off"></td>';
            str+='<td id="dj'+index+'">'+data.price+'</td>' +
              '<td id="sl'+index+'"><input autocomplete="off" class="form-control form-numArr" type="number" name="row[goods][goods_num][]"  value="1" placeholder="数量"></td>' +
              '<td id="zk'+index+'"><input autocomplete="off" class="form-control form-discountArr " type="text" name="row[goods][discount][]"  value="1" placeholder="例如：0.5"></td>' +
              '<td id="bz'+index+'"><input autocomplete="off" class="form-control" type="text" name="row[goods][remark][]" value="" placeholder="备注"></td>' +
              '<td id="sc'+index+'"><a data-id="'+index+'" style="cursor: pointer" class="del btn btn-xs btn-success btn-editone"><i class="fa fa-trash"></i></a></td>';
            str+='</tr>';
            $("#ultable").append(str);
            $("#sele"+index).selectPage({
              params:{'rows':index},
              andOr:'OR',
              eAjaxSuccess: function (data) {
                data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
                data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
                return data;
              },
              dropButton : false,
              eSelect : function(data) {
                var ind = this.params.rows;//当前行数
                $("#dj"+ind).html(data.price);
                $("#sl"+ind).find('input').focus();
              }
            });
            table_sort();
            index++;
          }
          //前面数字排序
          function table_sort() {
            var trs = $("#ultable tr");
            if (trs.length==0)return;
            for (var i=1;i<=trs.length;i++){
              trs.eq(i-1).find('td').eq(0).html(i);
            }
          }
          $(document).on("click", ".fagoods", function () {
            var product = $("input[name='gift']:checked").val();
            var goods_ids =  $('#goods_ids').val() ? $('#goods_ids').val()  : 0;
            var url = '';
            if(product == 2)
            {
              url = "store/finproduct/select?goods_ids=" + goods_ids + "&multiple=true&goods_ids="+ goods_ids;
            }else {
              url = "store/preproduct/select?goods_ids=" + goods_ids + "&multiple=true&goods_ids="+ goods_ids;
            }
            parent.Fast.api.open(url, __('Choose'), {
              callback: function (data) {
                if(data.multiple){//多选
                  var Html ='';
                  $.each(data.list, function (i, j) {
                    htmlAdd(j);
                  });
                }else{//单选
                  htmlAdd({id:data.ids,price:data.price});
                }
              }
            });
          });

          Controller.api.bindevent();
          $("#c-dep_id").change(function () {  
                var id = $(this).val();  
                $.ajax({
                  url: 'ajax/getAgentFenInfo/depid/'+id,
                  dataType: 'json',
                  success: function (res) {
                      //追加收货方
                      $('#c-consignee').val(res.consignee);
                      $('#c-consigneeTelephone').val(res.consigneeTelephone);
                      $('#c-consigneeAddress').val(res.consigneeAddress);
                      $('#c-nameAgent').val(res.gname);
                  }
                });
         });  
          require(['selectpage'], function () {
            $('#c-agent_name').selectPage({
              eAjaxSuccess: function (data) {
                data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
                data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
                return data;
              },
              eSelect : function(data){
                $.ajax({
                  url: 'ajax/getAgentFenInfo/depid/'+data.agent_name,
                  dataType: 'json',
                  success: function (res) {
                      //追加收货方
                      $('#c-consignee').val(res.consignee);
                      $('#c-consigneeTelephone').val(res.consigneeTelephone);
                      $('#c-consigneeAddress').val(res.consigneeAddress);
                  }
                });
              }
            });
          });

          //点击空白处，下拉框隐藏-------开始
          $(document).bind("click",function(e){//点击空白处，设置的弹框消失
            e.stopPropagation();//阻止事件冒泡
          });

          //批量修改折扣
          $(document).on('change','#c-discountArr',function (event) {
            $('.form-discountArr').val($('#c-discountArr').val());
          });
          //批量修改数量
          $(document).on('change','#c-numArr',function (event) {
            $('.form-numArr').val($('#c-numArr').val());
          });


        },
        edit: function () {
            Controller.api.bindevent();
        },
        status: function () {
          Controller.api.bindevent();
        },
        detail: function () {
          Controller.api.bindevent();
        },
        download: function () {
          Controller.api.bindevent();
           
        },
        send: function () {
            Controller.api.bindevent();

        },
        stat:function(){
          Controller.api.bindevent();
          require(['selectpage'], function () {
            $('#c-agent_name').selectPage({
              eAjaxSuccess: function (data) {
                data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
                data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
                return data;
              }
            });
          });

        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=download]"),function (data,ret) {
                  window.open(ret.url);
                });
                Form.api.bindevent($("form[role=stat]"),function (data,ret) {
                  $('.panel-stat').remove();
                  //展示表格
                  if(ret.code > 0)
                  {
                    $('.panel-intro').append(ret.data);
                    Toastr.success(ret.msg);
                  }
                  return false;
                },function (data, ret) {
                  if(ret.code == 0)
                  {
                    $('.panel-stat').remove();
                    Toastr.error(ret.msg);
                  }
                  return false;
                });
              Form.api.bindevent($("form[role=form]"));
            },
            formatter: {//渲染的方法
              status: function (value, row, index) {
                var color = 'success';
                if(row.status < 0)
                {
                  color = 'danger';
                }
                if(row.status == 0)
                {
                  color = 'yellow';
                }
                if(row.status == 8)
                {
                  color = 'danger';
                }
                return '<span class="text-'+color+'"><i class="fa fa-circle"></i>'+row.status_text+'</span>';
              },
              deliverystatus: function (value, row, index) {
                var color = 'success';
                if(row.status == 8)
                {
                  return '<span class="text-danger"><i class="fa fa-circle"></i>订单作废</span>';
                }
                if(row.deliverystatus < 0)
                {
                  color = 'danger';
                }
                if(row.deliverystatus == 0)
                {
                  color = 'yellow';
                }
                return '<span class="text-'+color+'"><i class="fa fa-circle"></i>'+row.deliverystatus_text+'</span>';
              }
            }
        }
    };
    return Controller;
});